package xin.ryven.workflow.service.impl;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import xin.ryven.workflow.dto.LoginRequest;
import xin.ryven.workflow.dto.LoginResponse;
import xin.ryven.workflow.security.JwtUtils;
import xin.ryven.workflow.security.UserDetailsImpl;
import xin.ryven.workflow.service.AuthService;

@Service
public class AuthServiceImpl implements AuthService {
    private final AuthenticationManager authenticationManager;
    private final JwtUtils jwtUtils;

    public AuthServiceImpl(AuthenticationManager authenticationManager, JwtUtils jwtUtils) {
        this.authenticationManager = authenticationManager;
        this.jwtUtils = jwtUtils;
    }

    @Override
    public LoginResponse login(LoginRequest request) {
        Authentication authentication = authenticationManager.authenticate(
            new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword())
        );

        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        String token = jwtUtils.generateToken(userDetails.getUsername());

        return LoginResponse.builder()
            .token(token)
            .id(userDetails.getId())
            .username(userDetails.getUsername())
            .fullName(userDetails.getFullName())
            .role(userDetails.getAuthorities().iterator().next().getAuthority())
            .build();
    }
} 